package com.banmao.desktoptools.util;

import javafx.application.Platform;
import javafx.scene.control.TextArea;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

@Slf4j
public class ResultOutput extends Thread {

    Boolean stopflag = false;

    final ByteArrayOutputStream bos;

    TextArea result_output;

    public ResultOutput(ByteArrayOutputStream bos, TextArea result_output) {
        this.bos = bos;
        this.result_output = result_output;
    }

    public void stopFlag() {
        this.stopflag = true;
    }

    @Override
    public void run() {
        try {
            //bos[0] = (ByteArrayOutputStream) getOutputStream();
            while (Thread.currentThread().isAlive() && !stopflag) {
                //synchronized (bos) {
                //ByteArrayOutputStream bos2 = new ByteArrayOutputStream();
                //bos.writeTo(bos2);
                bos.flush();
                String res = bos.toString(StandardCharsets.UTF_8);
                if (StringUtils.isNotBlank(res)) {
                    System.out.println("试图打印");
                    Platform.runLater(() -> {
                        result_output.appendText("测试输出：" + res);
                    });
                    bos.reset();
                }
                //}
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            log.info("进入finally");
            if(bos != null) {
                try {
                    bos.close();
                } catch (IOException ignored) {

                }
            }
        }
    }
}
